package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 标准农事 信息操作处理
 *
 * @author ruoyi
 * @date 2019-07-28
 */
@Controller
@RequestMapping("/system/ncWork")
public class NcWorkController extends BaseController {
    private String prefix = "system/ncWork";

    @Autowired
    private INcWorkService ncWorkService;
    @Autowired
    private INcStageService stageService;

    @Autowired
    private INcWorkMirrorService iNcWorkMirrorService;

    @Autowired
    private INcWorkLogService workLogService;

    @Autowired
    private INcStageMirrorService stageMirrorService;

    @Autowired
    private INcPlanService planService;

    @Autowired
    private INcPengInfoService pengInfoService;
    @Autowired
    private INcStandardService standardService;

    @RequiresPermissions("system:ncWork:view")
    @GetMapping()
    public String ncWork(ModelMap mmap) {
        return prefix + "/ncWork";
    }

    /**
     * 查询标准农事列表
     */
    @RequiresPermissions("system:ncWork:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcWork ncWork) {
        startPage();
        List<NcWork> list = ncWorkService.selectNcWorkList(ncWork);
        return getDataTable(list);
    }


    /**
     * 导出标准农事列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcWork ncWork) {
        List<NcWork> list = ncWorkService.selectNcWorkList(ncWork);
        ExcelUtil<NcWork> util = new ExcelUtil<NcWork>(NcWork.class);
        return util.exportExcel(list, "ncWork");
    }

    /**
     * 新增标准农事
     */
    @GetMapping("/add/{stageId}")
    public String add(@PathVariable long stageId, ModelMap mmap) {
        NcStage ncStage = stageService.selectNcStageById(stageId);
        long standardId = ncStage == null ? null : ncStage.getStandardId();
        mmap.put("stageId", stageId);
        mmap.put("standardId", standardId);

        return prefix + "/add";
    }

    /**
     * 新增保存标准农事
     */
    @RequiresPermissions("system:ncWork:add")
    @Log(title = "标准农事", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcWork ncWork) {
        return toAjax(ncWorkService.insertNcWork(ncWork));
    }

    /**
     * 修改标准农事
     */
    @GetMapping("/edit/{workId}")
    public String edit(@PathVariable("workId") Long workId, ModelMap mmap) {
        NcWork ncWork = ncWorkService.selectNcWorkById(workId);
        mmap.put("ncWork", ncWork);
        return prefix + "/edit";
    }

    /**
     * 修改保存标准农事
     */
    @RequiresPermissions("system:ncWork:edit")
    @Log(title = "标准农事", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcWork ncWork) {
        return toAjax(ncWorkService.updateNcWork(ncWork));
    }

    /**
     * 删除标准农事
     */
    @RequiresPermissions("system:ncWork:remove")
    @Log(title = "标准农事", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncWorkService.deleteNcWorkByIds(ids));
    }


    /**
     * 查询当天农事
     */
    @PostMapping("/listTodays")
    @ResponseBody
    public TableDataInfo listTodays(NcWork ncWork) {
        List<NcWorkMirror> list = ncWorkService.listTodays(ncWork, ShiroUtils.getSysUser());

        //自定义排序1
        Collections.sort(list, new Comparator<NcWorkMirror>() {
            @Override
            public int compare(NcWorkMirror o1, NcWorkMirror o2) {
                try {
                    return NcUtils.differentDaysByDate(o1.getWorkDate(), o2.getWorkDate());
                } catch (Exception e) {
                    return 0;
                }
            }
        });

        //TODO 需优化 sql查询 而不是遍历查询
        for (NcWorkMirror wm : list) {
            NcPlan plan = planService.selectNcPlanById(wm.getPlanId());
            wm.setPlan(plan);
            wm.setStandard(standardService.selectNcStandardById(plan.getStandardId()));

            NcStageMirror sm = new NcStageMirror();
            sm.setPlanId(wm.getPlanId());
            List<NcStageMirror> mirrors = stageMirrorService.selectNcStageMirrorList(sm);
            wm.setStages(mirrors);
        }
        return getDataTable(list);
    }

    /**
     * 查询正在执行农事阶段
     */
    @PostMapping("/listOnExe")
    @ResponseBody
    public TableDataInfo listOnExe(NcStageMirror mirror) {
        List<NcStageMirror> list = ncWorkService.listOnExe(mirror, ShiroUtils.getSysUser());
        //自定义排序1
        Collections.sort(list, new Comparator<NcStageMirror>() {
            @Override
            public int compare(NcStageMirror o1, NcStageMirror o2) {
                try {
                    return NcUtils.differentDaysByDate(o1.getWorkDate(), o2.getWorkDate());
                } catch (Exception e) {
                    return 0;
                }
            }
        });
//TODO 需优化 sql查询 而不是遍历查询
        for (NcStageMirror sm : list) {
            NcPlan plan = planService.selectNcPlanById(sm.getPlanId());
            sm.setPlan(plan);
            sm.setStandard(standardService.selectNcStandardById(plan.getStandardId()));

            NcStageMirror s = new NcStageMirror();
            s.setPlanId(sm.getPlanId());
            List<NcStageMirror> mirrors = stageMirrorService.selectNcStageMirrorList(s);
            sm.setStages(mirrors);
        }
        return getDataTable(list);
    }

    /**
     * 查待执行的农事计划
     */
    @PostMapping("/listpreExe")
    @ResponseBody
    public TableDataInfo listpreExe(NcPlan plan) {
        startPage();
        List<NcPlan> list = ncWorkService.listpreExe(plan, ShiroUtils.getSysUser());
        //TODO 需优化 sql查询 而不是遍历查询
        for (NcPlan sm : list) {
            NcStageMirror s = new NcStageMirror();
            s.setPlanId(sm.getPlanId());
            List<NcStageMirror> mirrors = stageMirrorService.selectNcStageMirrorList(s);
            sm.setStages(mirrors);

            sm.setStandard(standardService.selectNcStandardById(sm.getStandardId()));

        }
        return getDataTable(list);
    }

    /**
     * 确认执行
     */
    @PostMapping("/confirmWork")
    @ResponseBody
    public AjaxResult confirmWork(NcWorkMirror ncWork) {
        NcWorkMirror m = iNcWorkMirrorService.selectNcWorkMirrorById(ncWork.getWorkMirrorId());
        //1.工作状态为已完成
        m.setWorkStatus("1");
        m.setRemark(ncWork.getRemark());
        m.setInputCn(ncWork.getInputCn());
        m.setInput(ncWork.getInput());
        m.setInputCount(ncWork.getInputCount());
        m.setInputUnit(ncWork.getInputUnit());
        iNcWorkMirrorService.updateNcWorkMirror(m);
        //2 新增工作记录
        NcStageMirror stm = new NcStageMirror();
        stm.setPlanId(m.getPlanId());
        stm.setStageId(m.getStageId());
        List<NcStageMirror> stageMirrors = stageMirrorService.selectNcStageMirrorList(stm);

        if (stageMirrors != null && stageMirrors.size() > 0) {
            m.setStageMirrorId(stageMirrors.get(0).getStageMirrorId());
        }

        m.setCreateTime(ncWork.getCreateTime());
        NcWorkLog log = new NcWorkLog(m);
        log.setSource(1);
        log.setCreateBy(ShiroUtils.getLoginName());
        workLogService.insertNcWorkLog(log);
        /*阶段*/
        return AjaxResult.success(1);
    }

    /**
     * 确认执行
     */
    @PostMapping("/confirmStage")
    @ResponseBody
    public AjaxResult confirmStage(NcStageMirror stage) {
        NcStageMirror m = stageMirrorService.selectNcStageMirrorById(stage.getStageMirrorId());

        //工作

        /*更新阶段状态为已完成*/

        try {
            NcStageMirror sm = new NcStageMirror();
            sm.setStageMirrorId(m.getStageMirrorId());
            sm.setStageStatus("1");
            sm.setFinishTime(stage.getFinishTime());
            stageMirrorService.updateNcStageMirror(sm);
            Long planId = m.getPlanId();
            Long stageId = m.getStageId();
            setStageStatus(planId, stageId);
        } catch (Exception e) {
            return AjaxResult.success(0);
        }
        return AjaxResult.success(1);
    }

    /**
     * 推迟执行
     */
    @PostMapping("/delayDays")
    @ResponseBody
    public AjaxResult delayDays(NcStageMirror stage) {
        NcStageMirror m = stageMirrorService.selectNcStageMirrorById(stage.getStageMirrorId());
        m.setStageDays(m.getStageDays() + stage.getDelayDays());
        return AjaxResult.success(stageMirrorService.updateNcStageMirror(m));
    }

    /**
     * 设置阶段状态
     *
     * @param planId
     * @param stageId
     */
    private void setStageStatus(Long planId, Long stageId) {
        /*把下一阶段标为已开始如果是最后一个阶段 则结束该计划*/
        /*根据标准id获取所有的阶段*/
        NcStageMirror stm = new NcStageMirror();
        stm.setPlanId(planId);
        List<NcStageMirror> mirrors = stageMirrorService.selectNcStageMirrorList(stm);
        /*找到下一个阶段*/
        for (int i = 0; i < mirrors.size(); i++) {
            NcStageMirror obj = mirrors.get(i);
            if (stageId.equals(obj.getStageId())) {
                //最后一个阶段
                if (i == mirrors.size() - 1) {
                    NcPlan p = new NcPlan();
                    p.setPlanId(planId);
                    p.setStatus("4");//已完成
                    planService.updateNcPlan(p);
                } else {
                    NcStageMirror nextStage = mirrors.get(i + 1);
                    nextStage.setStageStatus("2");//执行中
                    stageMirrorService.updateNcStageMirror(nextStage);
                }
            }
        }
    }

    /**
     * 阶段提前结束
     */
    @PostMapping("/preFinish")
    @ResponseBody
    public AjaxResult preFinish(NcStageMirror stageMirror) {
        NcStageMirror s = new NcStageMirror();
        s.setStageId(stageMirror.getStageId());
        s.setStageStatus("1");
        s.setStageMirrorId(stageMirror.getStageMirrorId());
        s.setFinishTime(new Date());
        stageMirrorService.updateNcStageMirror(s);

        s = stageMirrorService.selectNcStageMirrorById(stageMirror.getStageMirrorId());
        //更新下一个阶段的 状态
        setStageStatus(s.getPlanId(), s.getStageId());
        return AjaxResult.success(1);

    }

    /**
     * 计划提前几天
     */
    @GetMapping("/preDays/{planId}")
    public String preDays(@PathVariable("planId") Long planId, ModelMap mmap) {
        NcPlan plan = planService.selectNcPlanById(planId);
        plan.setPreDays(NcUtils.differentDaysByDate(plan.getPlanTime(), new Date()));
        mmap.put("plan", plan);
        mmap.put("planId", planId);
        return prefix + "/edit-preDays";

    }

    /**
     * 计划推迟几天
     */
    @GetMapping("/delayDays/{planId}")
    public String delayDays(@PathVariable("planId") Long planId, ModelMap mmap) {
        NcPlan plan = planService.selectNcPlanById(planId);
        plan.setPreDays(NcUtils.differentDaysByDate(plan.getPlanTime(), new Date()));
        mmap.put("plan", plan);
        mmap.put("planId", planId);
        return prefix + "/edit-delayDays";

    }

    /**
     * 大棚信息
     */
    @GetMapping("/daPeng/{planId}")
    public String daPeng(@PathVariable("planId") Long planId, ModelMap mmap) {
        NcPlan plan = planService.selectNcPlanById(planId);
        mmap.put("plan", plan);
        mmap.put("planId", planId);
        return prefix + "/edit-daPeng";
    }

    /**
     * 大棚信息
     */
    @PostMapping("/daPeng")
    @ResponseBody
    public AjaxResult daPengSave(NcPlan plan, ModelMap mmap) {
        //校验
        NcPlan plan1 = planService.selectNcPlanById(plan.getPlanId());
        Double count = new Double(0);
        for (Map p : plan.getDaPengs()) {
            count += Double.parseDouble("" + p.get("area"));
        }
        if (count != plan1.getArea().doubleValue()) {
            return AjaxResult.error("面积与计划不符");
        }


        //清空之前的
        NcPengInfo tp = new NcPengInfo();
        tp.setPlanId(plan.getPlanId());
        List<NcPengInfo> infos = pengInfoService.selectNcPengInfoList(tp);
        for (NcPengInfo i : infos) {
            pengInfoService.deleteNcPengInfoByIds(i.getPengInfoId() + ",");
        }

        List<Map> daPengs = plan.getDaPengs();
        for (Map m : daPengs) {
            NcPengInfo p = new NcPengInfo();
            p.setPlanId(plan.getPlanId());
            p.setDeptId(Long.parseLong("" + m.get("deptId")));
            p.setDeptName("" + m.get("deptName"));
            p.setArea(new BigDecimal(Double.parseDouble("" + m.get("area"))));
            p.setCreateTime(new Date());
            p.setCreateBy(ShiroUtils.getLoginName());
            pengInfoService.insertNcPengInfo(p);
        }

        //处理标准

        return AjaxResult.success(1);
    }

    /**
     * 根据计划大棚信息
     */
    @PostMapping("/daPengList")
    @ResponseBody
    public TableDataInfo daPengList(NcPlan plan) {
        //清空之前的
        NcPengInfo tp = new NcPengInfo();
        tp.setPlanId(plan.getPlanId());
        List<NcPengInfo> infos = pengInfoService.selectNcPengInfoList(tp);
        return getDataTable(infos);
    }

    /**
     * 计划提前几天
     */
    @PostMapping("/preDays")
    @ResponseBody
    public AjaxResult preDaysEdit(NcPlan plan) {
        NcPlan db = planService.selectNcPlanById(plan.getPlanId());
        db.setPlanTime(DateUtils.addDays(db.getPlanTime(), -plan.getPreDays()));
        return AjaxResult.success(planService.updateNcPlan(db));

    }

    /**
     * 计划延迟几天
     */
    @PostMapping("/delayPlanDays")
    @ResponseBody
    public AjaxResult delayDaysEdit(NcPlan plan) {
        NcPlan db = planService.selectNcPlanById(plan.getPlanId());
        db.setPlanTime(DateUtils.addDays(db.getPlanTime(), plan.getPreDays()));
        return AjaxResult.success(planService.updateNcPlan(db));

    }

    /**
     * 修改计划
     */
    @GetMapping("/editPlan")
    public String editPlan(NcPlan plan, ModelMap mmap) {
        //校验
        NcPlan plan1 = planService.selectNcPlanById(plan.getPlanId());
        NcStandard st = new NcStandard();
        st.setCropVarieties(plan1.getCropVarieties());
        st.setStandardType("" + plan1.getPlanType());
        List<NcStandard> standards = standardService.selectNcStandardList(st);

        for (NcStandard s : standards) {
            if (s.getStandardId() == plan1.getStandardId()) {
                s.setFlag(true);
                break;
            }
        }
        mmap.put("standards", standards);
        mmap.put("planId", plan.getPlanId());
        return prefix + "/edit-plan-info";
    }


}
